package com.chen.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chen.entity.ChatMsg;
import com.chen.entity.User;
import com.chen.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * websocket
 *
 * @author chenchao
 * @date 2022/7/11 8:59
 */

@Controller
public class WsController {


    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private UserMapper userMapper;

    @MessageMapping("/ws/chat")
    public void handlerMsg(HttpServletRequest request, ChatMsg chatMsg) {
        String userId = request.getHeader("X-ID");
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", Integer.parseInt(userId));
        User user = userMapper.selectOne(queryWrapper);
        chatMsg.setFrom(user.getUsername());
        chatMsg.setFromNickname(user.getNick());
        chatMsg.setDate(LocalDateTime.now());
//        发送消息
        messagingTemplate.convertAndSendToUser(chatMsg.getTo(), "/queue/chat", chatMsg);
    }
}
